#!/usr/bin/python

import sys
from itertools import groupby

def main():
    input_fname = sys.argv[1]
    map_locus_fname = sys.argv[2]
    map_genes_fname = sys.argv[3]
    output_fname = sys.argv[4]

    locus_dict = {}
    output_file = open(output_fname, 'w')
    map_locus_file = open(map_locus_fname, 'w')
    map_genes_file = open(map_genes_fname, 'w')
    for gene_id, (gene, grp) in enumerate(groupby((line.split()[:2] for line in open(input_fname)), key=lambda i:i[0]), 1):
        gene_set = set()
        for gene, locus in grp:
            locus_id = locus_dict.get(locus)
            if not locus_id:
                locus_id = len(locus_dict) + 1
                locus_dict[locus] = locus_id
                map_locus_file.write("%s\t%s\n" % (locus, locus_id))
            gene_set.add(locus_id)
        output_file.write("%s\t%s\n" % (gene_id, ','.join(map(str,sorted(gene_set)))))
        map_genes_file.write("%s\t%s\n" % (gene, gene_id))
    output_file.close()
    map_genes_file.close()
    map_locus_file.close()
    

if __name__ == '__main__':
    
    main()
